import socket
import struct
import json
phone = socket.socket()

phone.connect(('127.0.0.1',8848))
while 1:
    to_server_data = input('>>>输入q或者Q退出').strip().encode('utf-8')
    if not to_server_data:
        # 服务端如果接受到了空的内容，服务端就会一直阻塞中，所以无论哪一端发送内容时，都不能为空发送
        print('发送内容不能为空')
        continue
    phone.send(to_server_data)
    if to_server_data.upper() == b'Q':
        break

    # 1. 接收固定长度的4个字节
    head_bytes = phone.recv(4)

    # 2. 获得bytes类型字典的总字节数
    len_head_dic_json_bytes = struct.unpack('i',head_bytes)[0]

    # 3. 接收bytes形式的dic数据
    head_dic_json_bytes = phone.recv(len_head_dic_json_bytes)

    # 4. 转化成json类型dic
    head_dic_json = head_dic_json_bytes.decode('utf-8')

    # 5. 转化成字典形式的报头
    head_dic = json.loads(head_dic_json)
    '''
    head_dic = {
                'file_name': 'test1',
                'md5': 6567657678678,
                'total_size': total_size,

            }
    '''
    total_data = b''
    while len(total_data) < head_dic['total_size']:
        total_data += phone.recv(1024)

    # print(len(total_data))
    print(total_data.decode('gbk'))

phone.close()



